<template>
  <div class="detail">
    <el-form
      label-width="120px"
      :model="detailData"
      :rules="rules.value"
      ref="ruleProduct"
    >
      <el-form-item v-if="pageStatus === 'edit'" label="商品编号：">
        {{ detailData.value.code }}
      </el-form-item>
      <el-form-item label="商品名称：" prop="name">
        <el-input placeholder="请输入商品名称" v-model="detailData.value.name" />
      </el-form-item>
      <el-form-item label="商品价格：¥" prop="price">
        <el-input-number
          :controls="false"
          placeholder="请输入商品价格"
          v-model="detailData.value.price"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="商品库存：" prop="stock">
        <el-input-number
          :controls="false"
          placeholder="请输入商品库存"
          v-model="detailData.value.stock"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="商品状态：">
        <el-select v-model="detailData.value.status" placeholder="请选择">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-row justify="center">
      <el-button @click="handleBackList">返回列表</el-button>
      <el-button
        v-if="pageStatus === 'add'"
        type="primary"
        @click="handleAddProduct"
        >新增商品</el-button
      >
      <el-button
        v-if="pageStatus === 'edit'"
        type="primary"
        @click="handleSaveProduct"
        >保存商品</el-button
      >
      <el-button
        v-if="pageStatus === 'edit'"
        type="danger"
        @click="handleDeleteProduct"
        >删除商品</el-button
      >
      {{pageStatus}}
    </el-row>
  </div>
</template>

<script lang="ts">
import { ref, reactive, onMounted, defineComponent } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getDetail, saveProduct, addProduct, deleteProduct } from "@/api/index";
import { generateCode } from "@/utils/tools";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "Edit",
  setup() {
    const ruleProduct = ref(null);
    let pageStatus = ref('edit') as any;
    const statusList = [
      { label: "正常", value: "1" },
      { label: "下架", value: "0" },
    ];

    const rules = reactive({
      value: {
        name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 3, message: "长度需要大于3个字符", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        stock: [{ required: true, message: "请输入商品库存", trigger: "blur" }],
      },
    } as any);

    let detailData = reactive({
      value: {
        code: "",
        name: "",
        price: "",
        stock: "",
        status: "",
      },
    } as any);

    const route = useRoute();
    const router = useRouter();

    onMounted(() => {
      init();
    });

    const init = async () => {
      console.log(route.query.code)
      if (route.query.code) {
        pageStatus = "edit";
        console.log(pageStatus)
        const id = route.query.code;
        const result = await getDetail(id);
        detailData.value = result;
      } else {
        pageStatus = "add";
      }
    };

    const handleBackList = () => {
      router.push("/");
    };

    const handleAddProduct = () => {
      let myRef: any = ruleProduct;
      myRef.validate(async (valid: any) => {
        if (valid) {
          const result = await addProduct(
            Object.assign({}, detailData, { code: generateCode })
          );
          if (result) {
            ElMessage.success("新增成功");
            handleBackList();
          }
        } else {
          return false;
        }
      });
    };

    const handleSaveProduct = async () => {
      let myRef: any = ruleProduct;
      myRef.validate(async (valid: any) => {
        if (valid) {
          const id = route.query.code;
          const result = await saveProduct({ id, ...detailData });
          if (result) {
            ElMessage.success("保存成功");
            handleBackList();
          }
        } else {
          return false;
        }
      });
    };

    const handleDeleteProduct = async () => {
      if (detailData.status === "1") {
        ElMessage.warning("请先下架商品之后再删除");
        return false;
      }

      const id = route.query.code;
      const result = await deleteProduct(id);
      if (result) {
        ElMessage.success("删除成功");
        handleBackList();
      }
    };

    return {
      pageStatus,
      statusList,
      ruleProduct,
      rules,
      detailData,
      handleBackList,
      handleAddProduct,
      handleSaveProduct,
      handleDeleteProduct
    }
  },
});
</script>
<style scoped>
.detail {
  width: 400px;
  margin: 10px auto;
}
.detail ul {
  list-style: none;
  text-align: left;
}
.detail li {
  padding: 10px 0;
}
</style>
